package com.hsd.netty.client;

import com.hsd.netty.client.cache.OverallStaticCache;
import com.hsd.netty.client.decoder.MessagePackDecoder;
import com.hsd.netty.client.encoder.MessagePackEncoder;
import com.hsd.netty.client.handler.LoginAuthRequestHandler;
import com.hsd.netty.client.handler.RemoteClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author s.he
 * on 2020/6/1
 */
@Service
public class Application implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    private ThreadPoolExecutor executor =
            new ThreadPoolExecutor(1, 1, 2000, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));

    private static final Integer port = 8081;

    private static final String address = "127.0.0.1";

    @Resource
    private MessagePackDecoder messagePackDecoder;

    @Autowired
    private MessagePackEncoder messagePackEncoder;

    @Autowired
    private LoginAuthRequestHandler loginAuthRequestHandler;

    @Autowired
    private RemoteClientHandler remoteClientHandler;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        run(address, port);
    }

    public void run(String address, Integer port) {
        logger.info("【尝试连接】 客户端正在连接服务器，服务器的ip为{}， 端口为:{}", address, port);
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workGroup)
                    .remoteAddress(new InetSocketAddress(address, port))
                    .channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline()
                            .addLast(new LengthFieldBasedFrameDecoder(65535, 0, 2 ,0, 2))
                            .addLast(messagePackDecoder)
                            .addLast(new LengthFieldPrepender(2))
                            .addLast(messagePackEncoder)
                            .addLast(loginAuthRequestHandler)
                            .addLast(remoteClientHandler);
                }
            });

            ChannelFuture future = bootstrap.connect(new InetSocketAddress(address, port)).sync();
            logger.info("【连接成功】 客户端成功连接服务器，服务器的ip为{}， 端口为:{}", address, port);
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            logger.error("【断线自动重连】" + e.getMessage());
            OverallStaticCache.clear();
            workGroup.shutdownGracefully();
        } finally {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(10);
                        Application.this.run(address, port);
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            });
        }
    }
}
